<template>
  <div class="app-container calendar-list-container">
      
    <div class="filter-container">
       <el-input @keyup.enter.native="handleFilter" style="width: 150px;" class="filter-item" :placeholder="$t('table.user_uid')" v-model="listQuery.uid">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 150px;" class="filter-item" :placeholder="$t('table.user_name')" v-model="listQuery.username">
      </el-input>
      <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.user_status" :placeholder="$t('table.user_status')">
        <el-option v-for="item in userStatusOptions" :key="item.key" :label="item.display_name" :value="item.key">
        </el-option>
      </el-select>
      <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.office" placeholder="工作室">
        <el-option v-for="item in officeOptions" :key="item.key" :label="item.display_name" :value="item.key">
        </el-option>
      </el-select>
      <treeselect class="filter-item" 
        :load-options="loadRootOptions"
        :options="dept_options_group"
        :auto-load-root-options="false"
        :multiple="true"
        :placeholder="$t('table.department')" 
        style="width: 200px;"
        v-model="listQuery.departments_arr" >
      </treeselect>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">{{$t('table.add')}}</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间"  fit highlight-current-row
      style="width: 100%">
      <el-table-column type="expand">
       <template slot-scope="props">
        <el-form label-position="left" inline class="demo-table-expand">
          <el-form-item :label="$t('table.user_uid')">
            <span>
             {{ props.row.uid }}
            </span>
          </el-form-item>
          <el-form-item  :label="$t('table.user_password')">
            <span>{{ props.row.user_password}}</span>
          </el-form-item>
          <el-form-item  :label="$t('table.user_name')">
            <span>{{ props.row.username }}</span>
          </el-form-item>
          <el-form-item  :label="$t('table.user_gender')">
            <span>{{ props.row.user_gender | genderFilter }}</span>
          </el-form-item>
          <el-form-item  :label="$t('table.user_status')">
            <span>{{ props.row.user_status | userStatusFilter }}</span>
          </el-form-item>
          <el-form-item  :label="$t('table.user_birthday_time')" >
            <span>{{ props.row.user_birthday_time | timeFilter('{y}-{m}-{d}') }}</span>
          </el-form-item>
          <el-form-item :label="$t('table.user_mobile_phone')">
            <span>{{ props.row.user_mobile_phone }}</span>
          </el-form-item>
          <el-form-item :label="$t('table.user_email')">
            <span>{{ props.row.user_email }}</span>
          </el-form-item>
          <el-form-item :label="$t('table.user_telephone')">
            <span>{{ props.row.user_telephone }}</span>
          </el-form-item>
          <el-form-item :label="$t('table.user_address')">
            <span>{{ props.row.user_address }}</span>
          </el-form-item>
          <el-form-item :label="$t('table.office')" >
            <span>{{ props.row.office | officeValFilter }}</span>
          </el-form-item>
          <el-form-item :label="$t('table.user_department')">
            <span>{{ props.row.department_name }}</span>
          </el-form-item>
          <el-form-item :label="$t('table.user_entry_time')">
            <span>{{ props.row.user_entry_time | timeFilter('{y}-{m}-{d}') }}</span>
          </el-form-item>
          <el-form-item label='岗位'>
            <span  v-if="props.row._ranks && props.row._ranks.length >0" >
              <span v-for="(item, index) in props.row._ranks" :key="item.id">
                <span>{{ item.rank_name }}</span> <span v-if="(index+1) !== props.row._ranks.length">,</span>
              </span>
            </span>
            <span v-else >暂未分配岗位</span>
            <!-- <span>{{ props.row.user_leave_time | timeFilter('{y}-{m}-{d}') }}</span> -->
          </el-form-item>
          <el-form-item label='权限' class="full-form-item">
            <span v-if="props.row._roles && props.row._roles.roles && props.row._roles.roles.length >0" >
              <span>{{ getShowRoleDesc(props.row._roles.roles) }}</span>
            </span>
            <span v-else >暂无</span>
          </el-form-item>
          <el-form-item label='可视客户' class="full-form-item">
            <span v-if="props.row._roles && props.row._roles.roles && props.row._roles.roles.length >0" >
               <span>{{ getShowViewClientRoleDesc(props.row._roles.roles) }}</span>
            </span>
          </el-form-item>
          <el-form-item label='可视项目' class="full-form-item">
            <span v-if="props.row._roles && props.row._roles.roles && props.row._roles.roles.length >0" >
               <span>{{ getShowViewProjectRoleDesc(props.row._roles.roles) }}</span>
            </span>
          </el-form-item>
          <el-form-item label='可视员工' class="full-form-item">
            <span v-if="props.row._roles && props.row._roles.roles && props.row._roles.roles.length >0" >
               <span>{{ getShowViewEmployeRoleDesc(props.row._roles.roles) }}</span>
            </span>
            
          </el-form-item>
          <el-form-item label='审批粒度' class="full-form-item">
            <span v-if="props.row._roles && props.row._roles.roles && props.row._roles.roles.length >0" >
               <span>{{ getShowCheckAllRoleDesc(props.row._roles.roles) }}</span>
            </span>
          </el-form-item>
          
          <el-form-item :label="$t('table.user_leave_time')" v-if="props.row.user_leave_time">
            <span>{{ props.row.user_leave_time | timeFilter('{y}-{m}-{d}') }}</span>
          </el-form-item>
        </el-form>
      </template>
    </el-table-column>
      <el-table-column align="center" :label="$t('table.user_uid')" min-width="100px" >
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">
            {{ scope.row.uid }} <svg-icon icon-class="edit" />
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.user_name')" width="80px" >
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.user_status')" width="80px" >
        <template slot-scope="scope">
          <el-tag>{{scope.row.user_status | userStatusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.user_telephone')" width="120px" >
        <template slot-scope="scope">
          <span>{{scope.row.user_telephone}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.user_department')" width="180px" >
        <template slot-scope="scope">
          <span>{{scope.row.department_name}}</span>
        </template>
      </el-table-column>  
      <el-table-column align="center" :label="$t('table.office')" width="100px" >
        <template slot-scope="scope">
          <span>{{ scope.row.office | officeValFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.user_gender')" width="60px" >
        <template slot-scope="scope">
          <span>{{scope.row.user_gender | genderFilter }}</span>
        </template>
      </el-table-column> 

      <el-table-column align="center" :label="$t('table.actions')" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click='handleRanks(scope.row)' >岗位</el-button>
          <!-- <el-button size="mini" type="success" @click='handleRoleArea(scope.row)' >权限</el-button> -->
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger"  @click="handleDelete(scope.row)" >{{$t('table.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
 
        <el-form-item :label="$t('table.user_uid')" prop="uid">
          <el-input v-model="temp.uid"></el-input>
        </el-form-item>

        <el-form-item :label="$t('table.user_password')" prop="user_password">
          <el-input v-model="temp.user_password"></el-input>
        </el-form-item>

        <el-form-item :label="$t('table.user_name')" prop="username">
          <el-input v-model="temp.username"></el-input>
        </el-form-item>

        <el-form-item :label="$t('table.user_status')" prop="user_status">
          <el-select class="filter-item" v-model="temp.user_status" placeholder="请选择">
            <el-option v-for="item in userStatusOptions" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('table.user_birthday_time')" prop="timestamp">
          <el-date-picker v-model="temp.user_birthday_time" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="timestamp" >
          </el-date-picker>
        </el-form-item>

        <el-form-item :label="$t('table.user_mobile_phone')" prop="user_mobile_phone">
           <el-input v-model="temp.user_mobile_phone"></el-input>
        </el-form-item> 

        <el-form-item :label="$t('table.user_email')" prop="email">
           <el-input v-model="temp.user_email"></el-input>
        </el-form-item> 

        <el-form-item :label="$t('table.user_telephone')"  prop="user_telephone">
           <el-input v-model="temp.user_telephone"></el-input>
        </el-form-item> 

        <el-form-item :label="$t('table.user_address')" >
           <el-input v-model="temp.user_address"></el-input>
        </el-form-item> 

        <el-form-item :label="$t('table.user_weixin_no')">
           <el-input v-model="temp.user_weixin_no"></el-input>
        </el-form-item> 

        <el-form-item :label="$t('table.user_gender')" >
          <el-select class="filter-item" v-model="temp.user_gender" placeholder="请选择">
            <el-option v-for="item in userGenderOptions" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item> 

        <el-form-item :label="$t('table.office')" prop="office">
          <el-select class="filter-item" v-model="temp.office" placeholder="请选择">
            <el-option v-for="item in officeOptions" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item> 

        <el-form-item :label="$t('table.user_department')"  prop="department_id">
          <treeselect 
            :options="departmentTreeOptions"  
            :show-count="true" 
            placeholder="请选择" 
            v-model="temp.department_id"/>
        </el-form-item>

        <el-form-item :label="$t('table.user_entry_time')" >
          <el-date-picker v-model="temp.user_entry_time" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="timestamp" >
          </el-date-picker>
        </el-form-item>

        <el-form-item :label="$t('table.user_leave_time')">
          <el-date-picker v-model="temp.user_leave_time" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="timestamp" >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="岗位分配" :visible.sync="dialogRankVisible">
      <template>
        <el-transfer
          v-model="ranksOfUserData"
          filterable
          :render-content="renderFunc"
          :titles="['未分配岗位', '已有岗位']"
          :button-texts="['移除', '分配']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          @change="handleChange"
          :data="ranksAllData">
        </el-transfer>
      </template>
    </el-dialog>
    <el-dialog title="权限分配" :visible.sync="dialogRoleAreaVisible">
      <template>
      </template>
    </el-dialog>
  </div>
</template>

<style>
  .transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
  }
</style>
<script>
import Static_Data from '@/data/index'
import API from '@/utils/backend_api'
import waves from '@/directive/waves' // 水波纹指令
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_ROOT_OPTIONS } from '@riophae/vue-treeselect'

export default {
  name: 'user',
  components: { Treeselect },
  directives: {
    waves
  },
  data() {
    API.department.tree().then(response => {
      const departmentTreeData = response.data
      departmentTreeData.map(item => {
        const departmentChildren = []
        if (item.children && item.children.length > 0) {
          item.children.map(subitem => {
            departmentChildren.push({ id: subitem.id, label: subitem.department_name })
          })
        }
        this.departmentTreeOptions.push({ id: item.id, label: item.department_name, children: departmentChildren })
      })
      console.log(this.departmentTreeOptions)
      return this.departmentTreeOptions
    })
    return {
      dept_options_group: null,
      renderFunc(h, option) {
        return <span>{ option.label }</span>
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        username: '',
        uid: '',
        departments: '',
        office: '',
        departments_arr: [],
        user_status: '',
        sort: '+id'
      },
      userStatusOptions: Static_Data.userStatus,
      userGenderOptions: Static_Data.gender,
      officeOptions: Static_Data.office,
      departmentTreeOptions: [],
      ranksOfUserData: [],
      ranksAllData: [],
      rolesData: [],
      temp: {
        uid: '',
        username: '',
        user_password: '',
        user_status: 'on',
        user_birthday_time: '',
        user_mobile_phone: '',
        user_email: '',
        user_telephone: '',
        user_address: '',
        user_weixin_no: '',
        user_gender: '0',
        user_entry_time: '',
        user_leave_time: '',
        department_id: '',
        user_avatar_url: '',
        user_note: '',
        office: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      op_user_id: '',
      dialogRankVisible: false,
      dialogRoleAreaVisible: false,
      rules: {
        uid: [{ required: true, message: '必填项', trigger: 'change' }],
        user_password: [{ required: true, message: '必填项', trigger: 'change' }],
        username: [{ required: true, message: '必填项', trigger: 'change' }],
        user_status: [{ required: true, message: '必选项', trigger: 'change' }],
        office: [{ required: true, message: '必选项', trigger: 'change' }],
        department_id: [
          { required: true, message: '必选项', trigger: ['blur', 'change'] }
        ]
      },
      downloadLoading: false,
      depts: []
    }
  },
  filters: {
  },
  created() {
    this.getList()
    API.rbac.roles().then(response => {
      console.log('roles then')
      console.log(response.data)
      if (response.data && response.data.length > 0) {
        response.data.map(item =>
          this.rolesData.push({ key: item.id, label: item.rolename })
        )
      }
      console.log(this.rolesData)
    })
    API.department.all({}).then(response => {
      console.log(response)
      response.data.map(item => {
        if (item.department_type === '1') {
          this.depts.push({ key: item.id, display_name: item.department_name })
        }
      })
    })
  },
  methods: {
    async loadRootOptions({ action, parentNode, callback }) {
      const rootOptions = []
      if (action === LOAD_ROOT_OPTIONS) {
        const response = await API.department.tree()
        const departmentTreeData = response.data
        departmentTreeData.map(item => {
          const departmentChildren = []
          if (item.children && item.children.length > 0) {
            item.children.map(subitem => {
              departmentChildren.push({ id: subitem.id, label: subitem.department_name, children: [] })
            })
          }
          rootOptions.push({ id: item.id, label: item.department_name, children: departmentChildren })
        })
        this.dept_options_group = rootOptions
      }
    },
    getOfficeName(office_id) {
      let value = ''
      this.officeOptions.map(item => {
        if (item.key === office_id) {
          value = item.display_name
        }
      })
      return value
    },
    getDeptName(dept_id) {
      let value = ''
      this.depts.map(item => {
        if (item.key === dept_id) {
          value = item.display_name
        }
      })
      return value
    },
    getShowViewClientRoleDesc(data) {
      let content = ''
      const len = data.length
      const show_depts = []
      const show_offices = []
      for (let index = 0; index < len; index++) {
        const element = data[index]
        if (element.indexOf('VIEW_CLIENT_DEPT_') >= 0) {
          show_depts.push(element.replace('VIEW_CLIENT_DEPT_', ''))
        }
        if (element.indexOf('VIEW_CLIENT_OFFICE_') >= 0) {
          show_offices.push(element.replace('VIEW_CLIENT_OFFICE_', ''))
        }
      }
      console.log(show_depts, show_offices)
      if (show_depts.length > 0) {
        let detpt_content = ''
        for (let index = 0; index < show_depts.length; index++) {
          const element = show_depts[index]
          detpt_content += this.getDeptName(element)
          if ((index + 1) !== show_depts.length) {
            detpt_content += ','
          }
        }
        if (detpt_content !== '') {
          content += '部门：[' + detpt_content + '] '
        }
      }
      if (show_offices.length > 0) {
        let office_content = ''
        for (let index = 0; index < show_offices.length; index++) {
          const element = show_offices[index]
          office_content += this.getOfficeName(element)
          if ((index + 1) !== show_offices.length) {
            office_content += ','
          }
        }
        if (office_content !== '') {
          content += '\n办公室：[' + office_content + ']'
        }
      }
      if (content === '') {
        content = '暂无'
      }
      return content
    },
    getShowViewProjectRoleDesc(data) {
      let content = ''
      const len = data.length
      const show_depts = []
      const show_offices = []
      for (let index = 0; index < len; index++) {
        const element = data[index]
        if (element.indexOf('VIEW_PROJECT_DEPT_') >= 0) {
          show_depts.push(element.replace('VIEW_PROJECT_DEPT_', ''))
        }
        if (element.indexOf('VIEW_PROJECT_OFFICE_') >= 0) {
          show_offices.push(element.replace('VIEW_PROJECT_OFFICE_', ''))
        }
      }
      console.log(show_depts, show_offices)
      if (show_depts.length > 0) {
        let detpt_content = ''
        for (let index = 0; index < show_depts.length; index++) {
          const element = show_depts[index]
          detpt_content += this.getDeptName(element)
          if ((index + 1) !== show_depts.length) {
            detpt_content += ','
          }
        }
        if (detpt_content !== '') {
          content += '部门：[' + detpt_content + '] '
        }
      }
      if (show_offices.length > 0) {
        let office_content = ''
        for (let index = 0; index < show_offices.length; index++) {
          const element = show_offices[index]
          office_content += this.getOfficeName(element)
          if ((index + 1) !== show_offices.length) {
            office_content += ','
          }
        }
        if (office_content !== '') {
          content += '\n办公室：[' + office_content + ']'
        }
      }
      if (content === '') {
        content = '暂无'
      }
      return content
    },
    getShowViewEmployeRoleDesc(data) {
      let content = ''
      const len = data.length
      const show_depts = []
      const show_offices = []
      for (let index = 0; index < len; index++) {
        const element = data[index]
        if (element.indexOf('VIEW_EMPLOYEE_DEPT_') >= 0) {
          show_depts.push(element.replace('VIEW_EMPLOYEE_DEPT_', ''))
        }
        if (element.indexOf('VIEW_EMPLOYEE_OFFICE_') >= 0) {
          show_offices.push(element.replace('VIEW_EMPLOYEE_OFFICE_', ''))
        }
      }
      console.log(show_depts, show_offices)
      if (show_depts.length > 0) {
        let detpt_content = ''
        for (let index = 0; index < show_depts.length; index++) {
          const element = show_depts[index]
          detpt_content += this.getDeptName(element)
          if ((index + 1) !== show_depts.length) {
            detpt_content += ','
          }
        }
        if (detpt_content !== '') {
          content += '部门：[' + detpt_content + '] '
        }
      }
      if (show_offices.length > 0) {
        let office_content = ''
        for (let index = 0; index < show_offices.length; index++) {
          const element = show_offices[index]
          office_content += this.getOfficeName(element)
          if ((index + 1) !== show_offices.length) {
            office_content += ','
          }
        }
        if (office_content !== '') {
          content += '\n办公室：[' + office_content + ']'
        }
      }
      if (content === '') {
        content = '暂无'
      }
      return content
    },
    getShowCheckAllRoleDesc(data) {
      let content = ''
      const len = data.length
      const show_depts = []
      const show_offices = []
      for (let index = 0; index < len; index++) {
        const element = data[index]
        if (element.indexOf('CHECK_ALL_DEPT_') >= 0) {
          show_depts.push(element.replace('CHECK_ALL_DEPT_', ''))
        }
        if (element.indexOf('CHECK_ALL_OFFICE_') >= 0) {
          show_offices.push(element.replace('CHECK_ALL_OFFICE_', ''))
        }
      }
      console.log(show_depts, show_offices)
      if (show_depts.length > 0) {
        let detpt_content = ''
        for (let index = 0; index < show_depts.length; index++) {
          const element = show_depts[index]
          detpt_content += this.getDeptName(element)
          if ((index + 1) !== show_depts.length) {
            detpt_content += ','
          }
        }
        if (detpt_content !== '') {
          content += '部门：[' + detpt_content + '] '
        }
      }
      if (show_offices.length > 0) {
        let office_content = ''
        for (let index = 0; index < show_offices.length; index++) {
          const element = show_offices[index]
          office_content += this.getOfficeName(element)
          if ((index + 1) !== show_offices.length) {
            office_content += ','
          }
        }
        if (office_content !== '') {
          content += '\n办公室：[' + office_content + ']'
        }
      }
      if (content === '') {
        content = '暂无'
      }
      return content
    },
    getShowRoleDesc(data) {
      let content = ''
      const len = data.length
      for (let index = 0; index < len; index++) {
        const element = data[index]
        const rolename = this.getRoleName(element)
        if (rolename !== '') {
          content += rolename
          if ((index + 1) !== len) {
            console.log(index, len)
            content += ' '
          }
        }
      }
      return content
    },
    getList() {
      this.listLoading = true
      console.log('api user query:')
      console.log(this.listQuery)
      this.listQuery.departments = JSON.stringify(this.listQuery.departments_arr)
      API.user.all(this.listQuery).then(response => {
        this.list = response.data
        if (response.headers && response.headers['x-total-count']) {
          this.total = Number(response.headers['x-total-count'])
        }
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleRoleArea(data) {
      this.dialogRoleAreaVisible = true
    },
    handleRanks(data) {
      this.ranksAllData.splice(0, this.ranksAllData.length)
      // 设置当前操作的职位
      this.op_user_id = data.id
      API.rank.all({}).then(response => {
        console.log(response.data)
        if (response.data && response.data.length > 0) {
          response.data.map(item =>
            this.ranksAllData.push({ key: item.id, label: item.rank_name })
          )
        }
      })
      console.log(data)
      API.user.ranks(data.id).then(response => {
        console.log('user ranks-------------')
        console.log(response)
        this.ranksOfUserData.splice(0, this.ranksOfUserData.length)
        response.data.map(item =>
          this.ranksOfUserData.push(item.id)
        )
        this.dialogRankVisible = true
      })
    },
    resetTemp() {
      this.temp = {
        uid: '',
        username: '',
        user_password: '',
        user_status: 'on',
        user_birthday_time: '',
        user_mobile_phone: '',
        user_email: '',
        user_telephone: '',
        user_address: '',
        user_weixin_no: '',
        user_gender: '0',
        user_entry_time: '',
        user_leave_time: '',
        department_id: '',
        user_avatar_url: '',
        user_note: '',
        office: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          API.user.add(this.temp).then((response) => {
            console.log(response)
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    getRoleName(id) {
      let value = ''
      this.rolesData.map(item => {
        if (item.key === id) {
          value = item.label
        }
      })
      return value
    },
    getViewRoleName(id) {

    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      if (row.department && row.department.id) {
        this.temp.department_id = row.department.id
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          API.user.update(tempData).then((response) => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, response.data)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.user.del(row.uid).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$notify({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleChange(value, direction, movedKeys) {
      if (direction === 'left') {
        console.log(movedKeys)
        movedKeys.map(item => {
          API.user.del_rank_from_user(this.op_user_id, item).then(response => {
            console.log('del_rank_from_user:' + item)
          })
        })
        // 移除
      } else if (direction === 'right') {
        // 分配
        console.log(movedKeys)
        movedKeys.map(item => {
          API.user.add_rank_to_user(this.op_user_id, item).then(response => {
            console.log('add_rank_to_user:' + item)
          })
        })
      } else {
        console.log(direction)
      }
    }
  }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .full-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
</style>